package org.exez.modules.visitor.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Sets;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.util.CollectionUtils;
import org.exez.common.exception.JeecgBootException;
import org.exez.common.system.vo.LoginUser;
import org.exez.common.util.DateUtils;
import org.exez.common.util.RedisUtil;
import org.exez.modules.monitor.service.RedisService;
import org.exez.modules.system.entity.SysUser;
import org.exez.modules.system.service.ISysUserService;
import org.exez.modules.system.util.VisitorBeanUtils;
import org.exez.modules.visitor.api.vo.WhiteListUpdateByApiVO;
import org.exez.modules.visitor.constant.Enum;
import org.exez.modules.visitor.constant.IdentityTypeEnum;
import org.exez.modules.visitor.dto.terminal.ReservationApplicationPushDTO;
import org.exez.modules.visitor.entity.*;
import org.exez.modules.visitor.mapper.WhiteListMapper;
import org.exez.modules.visitor.service.*;
import org.exez.modules.visitor.util.*;
import org.exez.modules.visitor.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @Description: 白名单
 * @Author: exez-boot
 * @Date: 2020-06-27
 * @Version: V1.0
 */
@Slf4j
@Service
public class WhiteListServiceImpl extends ServiceImpl<WhiteListMapper, WhiteList> implements IWhiteListService {

    @Value("${url.mogo-view}")
    private String fileView;

    @Value("${url.mogo-upload}")
    private String uploadUrl;

    @Value("${url.file-view}")
    private String fileRootPath;

    @Autowired
    private SjyService sjyService;


    @Autowired
    private ISysUserService userService;

    @Autowired
    private IInstitutionService institutionService;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private IPushWhiteListService pushWhiteListService;

    /*private IVisitorCarAuthorityService carAuthorityService;*/

    @Autowired
    private IInstitutionService iInstitutionService;

    @Autowired
    private RedisUtil redisUtil;

    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveWhiteList(WhiteList whiteList) {
        log.info("[{}]start: saveWhiteList()", System.currentTimeMillis());

        String key = "DAKAI_WHITELIST_";
        String dateFormatToString = DateUtils.getDateCutTwo();
        String keycf = key + dateFormatToString + whiteList.getWhiteName();
        if (redisUtil.hasKey(keycf)) {
            throw new JeecgBootException("请勿重复提交");
        } else {
            redisUtil.set(keycf, "1");
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        Date date = DateUtils.getDate();
        whiteList.setCreateTime(date);
        whiteList.setUpdateTime(date);
        whiteList.setDeleted(1);

        if (IdentityTypeEnum.IDENTITY_CARD.getIndex().equals(whiteList.getIdentityType())) {
            if (!RegexUtils.checkIdCard(whiteList.getIdentityValue())) {
                throw new JeecgBootException("请输入正确的身份证号：" + whiteList.getWhiteName());
            }
        }

        if (StringUtils.isNotBlank(whiteList.getWhiteMobile()) && !RegexUtils.checkMobile(whiteList.getWhiteMobile())) {
            throw new JeecgBootException("请输入正确的被访人手机号");
        }

        checkNumberPlate(whiteList);

        whiteList.setFacePhoto(whiteList.getFacePhoto().replace(fileView, ""));

        LambdaQueryWrapper<WhiteList> nameQueryWrapper = new LambdaQueryWrapper<>();
        nameQueryWrapper.eq(WhiteList::getInstitutionId, whiteList.getInstitutionId());
        nameQueryWrapper.eq(WhiteList::getDeleted, 1);

        String identityValue = whiteList.getIdentityValue();
        //校验是否重复
        check(nameQueryWrapper, identityValue, whiteList.getWhiteMobile());

        save(whiteList);
        //车辆限制
        //carAuthorityService.saveVisitorCarAuthority(whiteList.getNumberPlate(),whiteList.getId(),1);

        log.info("[{}]zhongtu: saveWhiteList()", System.currentTimeMillis());
        //添加推送记录
        ExecutorService executor = Executors.newFixedThreadPool(5);
        executor.submit(() ->
        saveWhiteList(sysUser.getInstitutionId(), whiteList, 1)
        );

        String s = AESSJY.AESjiami(whiteList.getId().toString());

        log.info("[{}]end: saveWhiteList()", System.currentTimeMillis());
        redisUtil.del(key);
        return s;
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateWhiteList(WhiteList whiteList) {

        if (IdentityTypeEnum.IDENTITY_CARD.getIndex().equals(whiteList.getIdentityType())) {
            if (!RegexUtils.checkIdCard(whiteList.getIdentityValue())) {
                throw new JeecgBootException("请输入正确的身份证号：" + whiteList.getWhiteName());
            }
        }

        if (IdentityTypeEnum.PASSPORT.getIndex().equals(whiteList.getIdentityType())) {
            if (StringUtils.isBlank(whiteList.getIdentityValue())) {
                throw new JeecgBootException("请输入正确的护照号：" + whiteList.getWhiteName());
            }
        }

        if (StringUtils.isNotBlank(whiteList.getWhiteMobile()) && !RegexUtils.checkMobile(whiteList.getWhiteMobile())) {
            throw new JeecgBootException("请输入正确的被访人手机号");
        }

        checkNumberPlate(whiteList);

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        whiteList.setUpdateBy(sysUser.getId());

        Date date = DateUtils.getDate();
        whiteList.setUpdateTime(date);

        LambdaQueryWrapper<WhiteList> nameQueryWrapper = new LambdaQueryWrapper<>();
        nameQueryWrapper.eq(WhiteList::getInstitutionId, whiteList.getInstitutionId());
        nameQueryWrapper.ne(WhiteList::getId, whiteList.getId());

        //校验是否重复
        check(nameQueryWrapper, whiteList.getIdentityValue(), whiteList.getWhiteMobile());


        if (StringUtils.isNotBlank(whiteList.getFacePhoto())) {
            whiteList.setFacePhoto(whiteList.getFacePhoto().replace(fileView, ""));
        }

        updateById(whiteList);

        //车辆限制
        //carAuthorityService.updateVisitorCarAuthority(whiteList.getNumberPlate(),whiteList.getId());

        //添加推送记录
        Integer type = 2;
        saveWhiteList(sysUser.getInstitutionId(), whiteList, type);

        return true;
    }

    /**
     * 校验车牌号
     * @param whiteList
     */
    private void checkNumberPlate(WhiteList whiteList) {
        if (StringUtils.isNotBlank(whiteList.getNumberPlate()) ) {
            String[] split = whiteList.getNumberPlate().split(",");
            List<String> list = Arrays.asList(split);
            HashSet<String> hashSet = new HashSet(list);
            if (list.size() != hashSet.size()){
                throw new JeecgBootException("不要输入详情的车牌号码");
            }

            for (String s : split) {
                if (!RegexUtils.checkNumberPlate(s)) {
                    throw new JeecgBootException("请输入正确的车牌号");
                }
            }
        }
    }

    @Override
    public boolean updateWhiteListByIdentityValue(WhiteListUpdateByApiVO whiteListUpdateVO) {
        Institution institutionByCode = institutionService.getInstitutionByCode(whiteListUpdateVO.getInstitutionCode());
        WhiteList whiteList  = new WhiteList();
        BeanUtils.copyProperties(whiteListUpdateVO,whiteList);
        whiteList.setInstitutionId(institutionByCode.getId());
        whiteList.setIdentityValue(AESSJY.AESjiemi(whiteList.getIdentityValue()));

        if (StringUtils.isNotBlank(whiteList.getWhiteMobile())) {
            whiteList.setWhiteMobile(AESSJY.AESjiemi(whiteList.getWhiteMobile()));
        }


        if (StringUtils.isNotBlank(whiteList.getFacePhoto())) {
            String facePhoto = UploadUtil.upload(uploadUrl, whiteList.getFacePhoto());
            whiteList.setFacePhoto(fileView + facePhoto);
        }

        return updateWhiteList(whiteList);
    }

    @Override
    public WhiteListVO getWhiteListById(Integer id) {
        WhiteList byId = getById(id);
        WhiteListVO whiteListVO = new WhiteListVO();
        BeanUtils.copyProperties(byId, whiteListVO);
        whiteListVO.setFacePhoto(fileView + whiteListVO.getFacePhoto());
        return whiteListVO;
    }

    @Override
    public boolean deletedWhiteList(List<WhiteList> whiteLists) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        updateBatchById(whiteLists);
        for (WhiteList whiteList : whiteLists) {

            //添加推送记录
            Integer type = 3;
            saveWhiteList(sysUser.getInstitutionId(), whiteList, type);
        }


        return true;
    }

    /**
     *
     * @param institutionId
     * @param whiteList
     * @param type 类型：1添加，2修改，3删除 4，禁用 5停用
     */
    private void saveWhiteList(String institutionId, WhiteList whiteList, Integer type) {

        List<Device> devices = deviceService.listDeviceByInstitutionId(Integer.parseInt(institutionId));
        Date datePush = DateUtils.getDate();
        List<PushWhiteList> pushWhiteLists = new ArrayList();

        for (Device device : devices) {
            PushWhiteList pushWhiteList = new PushWhiteList();
            pushWhiteList.setWhiteListId(whiteList.getId());
            pushWhiteList.setType(type);

            pushWhiteList.setInstitutionId(device.getInstitutionId());
            pushWhiteList.setInstitutionCode(device.getInstitutionCode());
            pushWhiteList.setDeviceId(device.getId());
            pushWhiteList.setDeviceName(device.getDeviceName());
            pushWhiteList.setDeviceCode(device.getDeviceCode());
            pushWhiteList.setDeviceIp(device.getDeviceIp());
            pushWhiteList.setDevicePort(device.getDevicePort());

            pushWhiteList.setPushStatus(0);
            pushWhiteList.setCreateTime(datePush);
            pushWhiteList.setUpdateTime(datePush);

            pushWhiteLists.add(pushWhiteList);
        }

        pushWhiteListService.saveBatch(pushWhiteLists);

        try {
            Map<String, List<PushWhiteList>> collect = pushWhiteLists.stream().collect(Collectors.groupingBy(e -> e.getType() + e.getDeviceCode()));
            TreeMap<String, List<PushWhiteList>> treeMap = new TreeMap(collect);

            ExecutorService executor = Executors.newFixedThreadPool(5);
            treeMap.forEach((e, k) ->
                    executor.submit(() ->
                            sjyService.pushWhiteToSjy(k))
            );

        } catch (Exception e) {
            log.info("[{}] error:",e.getMessage());
            return;
        }

    }

    @Override
    public IPage<WhiteListVO> listWhiteList(Page<WhiteList> page, LambdaQueryWrapper<WhiteList> queryWrapper) {

        IPage<WhiteListVO> whiteListVOIPage = new Page<>();
        List<WhiteListVO> whiteListVOS = new ArrayList();

        IPage<WhiteList> whiteListIPage = baseMapper.selectPage(page, queryWrapper);

        BeanUtils.copyProperties(whiteListIPage, whiteListVOIPage);

        List<WhiteList> records = whiteListIPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            whiteListVOIPage.setRecords(whiteListVOS);
            return whiteListVOIPage;
        }

        whiteListVOS = VisitorBeanUtils.convertList2List(records, WhiteListVO.class);

        //创建人 车辆信息细化
        for (WhiteListVO whiteListVO : whiteListVOS) {
            SysUser byId = userService.getById(whiteListVO.getCreateBy());
            if (byId != null) {
                whiteListVO.setCreateByName(byId.getUsername());
            }

            if (StringUtils.isNotBlank(whiteListVO.getNumberPlate())) {
                String[] split = whiteListVO.getNumberPlate().split(",");
                int length = split.length;
                whiteListVO.setNumberPlateCount(length);
            }

            if (StringUtils.isNotBlank(whiteListVO.getFacePhoto())) {
                whiteListVO.setFacePhoto(fileView + whiteListVO.getFacePhoto());
            }

            whiteListVO.setWhiteName(AES.nameXx(whiteListVO.getWhiteName()));
            whiteListVO.setWhiteMobile(AES.mobileIdCardHide(whiteListVO.getWhiteMobile()));
            whiteListVO.setIdentityValue(AES.mobileIdCardHide(whiteListVO.getIdentityValue()));


        }
        whiteListVOIPage.setRecords(whiteListVOS);
        return whiteListVOIPage;
    }

    /**
     * 校验手机号和身份证是否重复
     * @param nameQueryWrapper
     * @param identityValue
     * @param mobile
     */
    private void check(LambdaQueryWrapper<WhiteList> nameQueryWrapper, String identityValue, String mobile) {
        LambdaQueryWrapper<WhiteList> mobileQueryWrapper = nameQueryWrapper.clone();
        LambdaQueryWrapper<WhiteList> identityValueQueryWrapper = nameQueryWrapper.clone();

        if (StringUtils.isNotBlank(mobile)) {
            mobileQueryWrapper.eq(WhiteList::getWhiteMobile, mobile);
            Integer mobileCount = baseMapper.selectCount(mobileQueryWrapper);
            if (mobileCount > 0) {
                throw new JeecgBootException("该单位已经存在该手机号");
            }
        }

        if (StringUtils.isNotBlank(identityValue)) {
            identityValueQueryWrapper.eq(WhiteList::getIdentityValue, identityValue);
            Integer identityValueCount = baseMapper.selectCount(identityValueQueryWrapper);
            if (identityValueCount > 0) {
                throw new JeecgBootException("该单位已经存在该证件号");
            }
        }

    }

    @Override
    public List<Integer> imPortExcl(List<WhiteListVOExcl> whiteListsVOExcl) throws Exception {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //whiteLists = whiteLists.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(WhiteList :: getIdentityValue))), ArrayList::new));
        List<WhiteList> success = new ArrayList<>();
        List<String> sfz = new ArrayList<>();

        //List<WhiteListExclVo> failed = new ArrayList<>();
        List<Integer> failed = new ArrayList<>();
        Date date = DateUtils.getDate();

        if (!CollectionUtils.isEmpty(whiteListsVOExcl)) {
            String mobile = null;
            for (int i = 0; i < whiteListsVOExcl.size(); i++) {
                WhiteListVOExcl whiteList = whiteListsVOExcl.get(i);
                if (whiteList.get车牌号() != null) {
                    whiteList.set车牌号(whiteList.get车牌号().replace("，", ","));
                }
                if (!sfz.contains(whiteList.get证件号码())) {
                    sfz.add(whiteList.get证件号码());
                } else {
                    failed.add(i + 2);
                    continue;
                }
                int institutionId = Integer.parseInt(sysUser.getInstitutionId());
                WhiteListExclVo whiteListVo = new WhiteListExclVo();
                whiteListVo.setInstitutionId(institutionId);
                whiteListVo.setWhiteName(whiteList.get姓名());
                whiteListVo.setWhiteMobile(whiteList.get手机号码());
                whiteListVo.setIdentityType(whiteList.get证件类型1身份证2护照());
                whiteListVo.setIdentityValue(whiteList.get证件号码());
                whiteListVo.setWorkNo(whiteList.get工作证号());
                whiteListVo.setNumberPlate(whiteList.get车牌号());

                String whiteName = whiteList.get姓名();
                String whiteMobile = whiteList.get手机号码();
                int identityType = whiteList.get证件类型1身份证2护照();
                String identityValue = whiteList.get证件号码();
                String workNo = whiteList.get工作证号();
                String numberPlate = whiteList.get车牌号();

                if (institutionId == 0) {
                    failed.add(i + 2);
                    continue;
                }
                if (!StringUtils.isNotEmpty(whiteName)) {
                    failed.add(i + 2);
                    continue;
                }
                if (!StringUtils.isNotEmpty(whiteMobile) && whiteMobile.trim().length() > 11) {
                    failed.add(i + 2);
                    continue;
                }
                if (identityType != 1 && identityType != 2) {
                    failed.add(i + 2);
                    continue;
                }

                if (whiteList.get证件类型1身份证2护照() != null && whiteList.get证件类型1身份证2护照() >= 0 && whiteList.get证件类型1身份证2护照() <= 2 && StringUtils.isNotEmpty(whiteList.get证件号码())) {
                    identityValue = whiteList.get证件号码().trim();
                    if (whiteList.get证件类型1身份证2护照() == 1) {
                        if (identityValue.length() != 18) {
                            failed.add(i + 2);
                            continue;
                        }
                    }
                    LambdaQueryWrapper<WhiteList> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(WhiteList::getIdentityValue, identityValue);
                    queryWrapper.eq(WhiteList::getDeleted, 1);
                    queryWrapper.eq(WhiteList::getInstitutionId, sysUser.getInstitutionId());
                    if (baseMapper.selectCount(queryWrapper) != 0) {//身份证重复了
                        failed.add(i + 2);
                        continue;
                    }
                } else {//身份证类型   号码必须18位
                    failed.add(i + 2);
                    continue;
                }
                WhiteList whiteList1 = new WhiteList();
                whiteList1.setInstitutionId(institutionId);
                whiteList1.setWhiteName(whiteName.trim());
                whiteList1.setWhiteMobile(whiteMobile.trim());
                whiteList1.setIdentityType(identityType);
                whiteList1.setIdentityValue(identityValue.trim());
                if (workNo != null) {
                    whiteList1.setWorkNo(workNo.trim());
                }
                if (numberPlate != null) {
                    whiteList1.setNumberPlate(numberPlate.trim());
                }

                whiteList1.setUpdateTime(date);
                whiteList1.setCreateTime(date);
                whiteList1.setUpdateBy(sysUser.getId());
                whiteList1.setCreateBy(sysUser.getId());


                /*String code = "";
                if(StringUtils.isNotEmpty(identityValue)){
                    File file = new File("D://face//"+identityValue.trim()+".jpg");
                    if(file.exists()){
                        code = UploadUtil.upload(uploadUrl, UploadUtil.encodeBase64File("D:/face/" + identityValue.trim()+".jpg"));
                    }
                    File file1 = new File("D://face//"+identityValue.trim()+".png");
                    if(file1.exists()){
                        String aaa = UploadUtil.encodeBase64File("D:/face/" + identityValue.trim()+".png");
                        code = UploadUtil.upload(uploadUrl, UploadUtil.encodeBase64File("D:/face/" + identityValue.trim()+".png"));
                    }
                }
                whiteList1.setFacePhoto(code);*/

                success.add(whiteList1);
            }
            this.saveBatch(success);
        }
        return failed;
    }


    @Override
    public List<Integer> imPortExclTest(List<WhiteListVOExcl> whiteListsVOExcl) throws Exception {

        List<String> aa =  UploadUtil.getAllFile("D:/face1", false);
        /*for (int i = 0; i < aa.size(); i++) {
            String s = aa.get(i);


        }*/

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //whiteLists = whiteLists.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(WhiteList :: getIdentityValue))), ArrayList::new));
        List<WhiteList> success = new ArrayList<>();
        List<String> sfz = new ArrayList<>();

        //List<WhiteListExclVo> failed = new ArrayList<>();
        List<Integer> failed = new ArrayList<>();
        Date date = DateUtils.getDate();

        if (!CollectionUtils.isEmpty(whiteListsVOExcl)) {
            String mobile = null;
            for (int i = 0; i < whiteListsVOExcl.size(); i++) {
                WhiteListVOExcl whiteList = whiteListsVOExcl.get(i);
                if (whiteList.get车牌号() != null) {
                    whiteList.set车牌号(whiteList.get车牌号().replace("，", ","));
                }
                if (!sfz.contains(whiteList.get证件号码())) {
                    sfz.add(whiteList.get证件号码());
                } else {
                    failed.add(i + 2);
                    continue;
                }
                int institutionId = Integer.parseInt(sysUser.getInstitutionId());
                WhiteListExclVo whiteListVo = new WhiteListExclVo();
                whiteListVo.setInstitutionId(institutionId);
                whiteListVo.setWhiteName(whiteList.get姓名());
                whiteListVo.setWhiteMobile(whiteList.get手机号码());
                whiteListVo.setIdentityType(whiteList.get证件类型1身份证2护照());
                whiteListVo.setIdentityValue(whiteList.get证件号码());
                whiteListVo.setWorkNo(whiteList.get工作证号());
                whiteListVo.setNumberPlate(whiteList.get车牌号());

                String whiteName = whiteList.get姓名();
                String whiteMobile = whiteList.get手机号码();
                int identityType = whiteList.get证件类型1身份证2护照();
                String identityValue = whiteList.get证件号码();
                String workNo = whiteList.get工作证号();
                String numberPlate = whiteList.get车牌号();

                if (institutionId == 0) {
                    failed.add(i + 2);
                    continue;
                }
                if (!StringUtils.isNotEmpty(whiteName)) {
                    failed.add(i + 2);
                    continue;
                }
                if (!StringUtils.isNotEmpty(whiteMobile) && whiteMobile.trim().length() > 11) {
                    failed.add(i + 2);
                    continue;
                }
                if (identityType != 1 && identityType != 2) {
                    failed.add(i + 2);
                    continue;
                }

                if (whiteList.get证件类型1身份证2护照() != null && whiteList.get证件类型1身份证2护照() >= 0 && whiteList.get证件类型1身份证2护照() <= 2 && StringUtils.isNotEmpty(whiteList.get证件号码())) {
                    identityValue = whiteList.get证件号码().trim();
                    if (whiteList.get证件类型1身份证2护照() == 1) {
                        if (identityValue.length() != 18) {
                            failed.add(i + 2);
                            continue;
                        }
                    }
                    /*LambdaQueryWrapper<WhiteList> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(WhiteList::getIdentityValue, identityValue);
                    queryWrapper.eq(WhiteList::getDeleted, 1);
                    queryWrapper.eq(WhiteList::getInstitutionId, sysUser.getInstitutionId());
                    if (baseMapper.selectCount(queryWrapper) != 0) {//身份证重复了
                        failed.add(i + 2);
                        continue;
                    }*/
                } else {//身份证类型   号码必须18位
                    failed.add(i + 2);
                    continue;
                }
                WhiteList whiteList1 = new WhiteList();
                whiteList1.setInstitutionId(institutionId);
                whiteList1.setWhiteName(whiteName.trim());
                whiteList1.setWhiteMobile(whiteMobile.trim());
                whiteList1.setIdentityType(identityType);
                whiteList1.setIdentityValue(identityValue.trim());
                if (workNo != null) {
                    whiteList1.setWorkNo(workNo.trim());
                }
                if (numberPlate != null) {
                    whiteList1.setNumberPlate(numberPlate.trim());
                }

                whiteList1.setUpdateTime(date);
                whiteList1.setCreateTime(date);
                whiteList1.setUpdateBy(sysUser.getId());
                whiteList1.setCreateBy(sysUser.getId());
                String code = "";
                String imagePath = "本地图片路径";

                String base64 = UploadUtil.encodeBase64File(aa.get(6000+i));
                code = UploadUtil.upload(uploadUrl, base64.replaceAll("\r|\n", ""));

                /*String code = "";
                if(StringUtils.isNotEmpty(identityValue)){
                    File file = new File("D://face//"+identityValue.trim()+".jpg");
                    if(file.exists()){
                        code = UploadUtil.upload(uploadUrl, UploadUtil.encodeBase64File("D:/face/" + identityValue.trim()+".jpg"));
                    }
                    File file1 = new File("D://face//"+identityValue.trim()+".png");
                    if(file1.exists()){
                        String aaa = UploadUtil.encodeBase64File("D:/face/" + identityValue.trim()+".png");
                        code = UploadUtil.upload(uploadUrl, UploadUtil.encodeBase64File("D:/face/" + identityValue.trim()+".png"));
                    }
                }
                whiteList1.setFacePhoto(code);*/

                whiteList1.setFacePhoto(code);
                success.add(whiteList1);
            }
            this.saveBatch(success);
            //添加推送记录
            ExecutorService executor = Executors.newFixedThreadPool(10);
            for (WhiteList whiteList : success) {
                executor.submit(() ->
                        saveWhiteList(sysUser.getInstitutionId(), whiteList, 1)
                );
            }

        }
        return failed;
    }

    @Override
    public void imPortPhoto(MultipartFile file) throws Exception {
        UploadUtil.getSplitFile(file.getBytes().toString(),5);


    }



    @Override
    public String chunkUploadByMappedByteBuffer1(MultipartFileParams param, String name) throws Exception {

        String filePath = "";
        try {
            if(param.getTaskId() == null || "".equals(param.getTaskId())){
                param.setTaskId(UUID.randomUUID().toString());
            }
            /**
             *
             * 1：创建临时文件，和源文件一个路径
             * 2：如果文件路径不存在重新创建
             */
            if(UploadUtil.isOSLinux()){
                filePath = fileRootPath;
            }else{
                filePath = Enum.whiteWindowsPath.getName();
            }
            String fileName = name;
            String tempFileName = param.getTaskId() + fileName.substring(fileName.lastIndexOf(".")) + "_tmp";
            File fileDir = new File(filePath);
            if(!fileDir.exists()){
                fileDir.mkdirs();
            }
            File tempFile = new File(filePath,tempFileName);
            //第一步
            RandomAccessFile raf = new RandomAccessFile(tempFile,"rw");
            //第二步
            FileChannel fileChannel = raf.getChannel();
            //第三步 计算偏移量
            long position = (param.getChunkNumber()-1) * param.getChunkSize();
            //第四步
            byte[] fileData = param.getFile().getBytes();
            //第五步
            long end=position+fileData.length-1;
            fileChannel.position(position);
            fileChannel.write(ByteBuffer.wrap(fileData));
            //使用 fileChannel.map的方式速度更快，但是容易产生IO操作，无建议使用
//        MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE,position,fileData.length);
//        //第六步
//        mappedByteBuffer.put(fileData);
            //第七步
//        freedMappedByteBuffer(mappedByteBuffer);
//        Method method = FileChannelImpl.class.getDeclaredMethod("unmap", MappedByteBuffer.class);
//        method.setAccessible(true);
//        method.invoke(FileChannelImpl.class, mappedByteBuffer);
            fileChannel.force(true);
            fileChannel.close();
            raf.close();
            //第八步
            boolean isComplete = checkUploadStatus1(param,fileName,filePath);
            String temp = Calendar.getInstance().getTimeInMillis()+"";
            if(isComplete){

                renameFile(tempFile,temp+".zip");
            }
            File file = new File(filePath + temp+".zip");
            UploadUtil.unZip(file,filePath);
            String temp111 = filePath + name.substring(0,name.indexOf("."));
            List fileList = UploadUtil.getFileList(temp111);
            //List fileList = UploadUtil.getFileList("d://face7");
            String srePath = "";
            String code = "";
            for (int i = 0; i < fileList.size(); i++) {
                System.out.println("进入了service层！！！！！！！！！！！！！！！！！！！"+srePath);
                srePath = fileList.get(i).toString().replaceAll("\\\\","/");
                System.out.println("替换后的！！！！！！！！！！！！！！！！！！！"+srePath);
                File file1 = new File(srePath);
                System.out.println("图片长度QQQQQQQQQQ" + file1.length());
                code = UploadUtil.upload(uploadUrl, UploadUtil.encodeBase64File(srePath).replaceAll("\r|\n", ""));
                //身份证
                srePath = srePath.replaceAll(" ","");
                if(srePath.contains(".")){
                    srePath = srePath.substring(srePath.lastIndexOf("/")+1, srePath.indexOf("."));
                    updatePhoto(srePath, code);
                }
            }
            String sre = filePath + name.substring(0,name.indexOf("."));
            UploadUtil.deleteDirectory(filePath + name.substring(0,name.indexOf(".")));
            UploadUtil.deleteFile(filePath +temp+".zip");
        }catch (Exception e){
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

        return param.getTaskId();
    }



    @Override
    public void updatePhoto(String idCard, String code) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if(idCard.contains("/")){
            idCard = idCard.substring(idCard.lastIndexOf("/") + 1);
        }
        if(idCard.contains("\\")){
            idCard = idCard.substring(idCard.lastIndexOf("\\") + 1);
        }
        LambdaQueryWrapper<WhiteList> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(WhiteList::getIdentityValue, idCard);
        queryWrapper.eq(WhiteList::getInstitutionId, sysUser.getInstitutionId());
        List<WhiteList> whiteLists = baseMapper.selectList(queryWrapper);
        for (int i = 0; i < whiteLists.size(); i++) {
            WhiteList whiteList = whiteLists.get(i);
            whiteList.setFacePhoto(code);
            baseMapper.updateById(whiteList);
            saveWhiteList(whiteList.getInstitutionId().toString(),whiteList,2);
        }

    }

    @Override
    public void policePay(String url ,String secret,String payId) {
        //公安pay代码
        url = url + "";
        Long timestamp = System.currentTimeMillis();
        String sign = secret + timestamp;
        String s = MD5.md5(sign);
        JSONObject json1 = new JSONObject();
        json1.put("time",timestamp);
        json1.put("payId",payId);
        json1.put("sign",sign);

        JSONObject json = new JSONObject();
        json.put("method", "connectCheck");
        json.put("data", json1);
        String s1 = HttpClientUtil.sendHttpPost(url, json.toJSONString());
        System.out.println(s1);



        JSONObject psInfo_1 = new JSONObject();
        psInfo_1.put("pageIndex",1);
        psInfo_1.put("pageSize",100);

        JSONObject psInfo = new JSONObject();
        psInfo.put("method", "getUserInfo");
        psInfo.put("data", psInfo_1);
        String psInfos = HttpClientUtil.sendHttpPost(url, psInfo.toJSONString());
        System.out.println(psInfos);


    }

    @Override
    public void insertWhite(WhiteList whiteList) {
        baseMapper.insert(whiteList);
    }


    /**
     * 文件重命名
     * @param toBeRenamed   将要修改名字的文件
     * @param toFileNewName 新的名字
     * @return
     */
    public boolean renameFile(File toBeRenamed, String toFileNewName) {
        //检查要重命名的文件是否存在，是否是文件
        if (!toBeRenamed.exists() || toBeRenamed.isDirectory()) {
            return false;
        }
        String p = toBeRenamed.getParent();
        File newFile = new File(p + File.separatorChar + toFileNewName);
        //修改文件名
        return toBeRenamed.renameTo(newFile);
    }

    /**
     * 检查文件上传进度
     * @return
     */
    public boolean checkUploadStatus1(MultipartFileParams param,String fileName,String filePath) throws IOException {
        File confFile = new File(filePath,fileName+".conf");
        RandomAccessFile confAccessFile = new RandomAccessFile(confFile,"rw");
        //设置文件长度
        confAccessFile.setLength(param.getTotalChunks());
        //设置起始偏移量
        confAccessFile.seek(param.getChunkNumber()-1);
        //将指定的一个字节写入文件中 127，
        confAccessFile.write(Byte.MAX_VALUE);
        byte[] completeStatusList = FileUtils.readFileToByteArray(confFile);
        confAccessFile.close();//不关闭会造成无法占用
        //这一段逻辑有点复杂，看的时候思考了好久，创建conf文件文件长度为总分片数，每上传一个分块即向conf文件中写入一个127，那么没上传的位置就是默认的0,已上传的就是Byte.MAX_VALUE 127
        for(int i = 0; i<completeStatusList.length; i++){
            if(completeStatusList[i]!=Byte.MAX_VALUE){
                return false;
            }
        }
        //如果全部文件上传完成，删除conf文件
        confFile.delete();
        return true;
    }


    @Override
    public void pushSaveOrUpdate() {
        LambdaQueryWrapper<WhiteList> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(WhiteList:: getDeleted,2,3);
        List<WhiteList> whiteLists = baseMapper.selectList(queryWrapper);

        Date date = DateUtils.getDate();
        List<PushWhiteList> pushWhiteLists = new ArrayList();
        for (WhiteList whiteList : whiteLists) {
            Integer institutionId = whiteList.getInstitutionId();
            List<Device> devices = deviceService.listDeviceByInstitutionId(institutionId);

            for (Device device : devices) {
                PushWhiteList pushWhiteList = new PushWhiteList();
                pushWhiteList.setWhiteListId(whiteList.getId());
                if (whiteList.getDeleted() ==2){
                    pushWhiteList.setType(1);
                }else {
                    pushWhiteList.setType(3);
                    PushWhiteList byPushWhiteListIdSave = pushWhiteListService.getByPushWhiteListIdSave(whiteList.getId());
                    if (byPushWhiteListIdSave == null) {
                        continue;
                    }
                    pushWhiteList.setPushId(byPushWhiteListIdSave.getPushId());
                }

                pushWhiteList.setInstitutionId(device.getInstitutionId());
                pushWhiteList.setInstitutionCode(device.getInstitutionCode());
                pushWhiteList.setDeviceId(device.getId());
                pushWhiteList.setDeviceName(device.getDeviceName());
                pushWhiteList.setDeviceCode(device.getDeviceCode());
                pushWhiteList.setDeviceIp(device.getDeviceIp());
                pushWhiteList.setDevicePort(device.getDevicePort());

                pushWhiteList.setPushStatus(0);
                pushWhiteList.setCreateTime(date);
                pushWhiteList.setUpdateTime(date);

                pushWhiteLists.add(pushWhiteList);
            }
            if (whiteList.getDeleted() == 2){
                whiteList.setDeleted(1);
            }else {
                whiteList.setDeleted(0);
            }
        }
        pushWhiteListService.saveBatch(pushWhiteLists);

        updateBatchById(whiteLists);

        try {
            Map<String, List<PushWhiteList>> collect = pushWhiteLists.stream().collect(Collectors.groupingBy(e -> e.getType() + e.getDeviceCode()));
            TreeMap<String, List<PushWhiteList>> treeMap = new TreeMap(collect);

            //添加推送记录
            ExecutorService executor = Executors.newFixedThreadPool(5);
            treeMap.forEach((e, k) ->
                    executor.submit(() ->
                            sjyService.pushWhiteToSjy(k))
            );

        } catch (Exception e) {
            log.info("[{}] error:",e.getMessage());
            return;
        }
    }

    @Override
    public void batchSyncWhiteList() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<WhiteList> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(WhiteList::getCreateBy,sysUser.getId());
        queryWrapper.eq(WhiteList::getDeleted,1);
        queryWrapper.isNull(WhiteList::getFacePhoto);
        List<WhiteList> list = this.list(queryWrapper);
        //添加推送记录
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (WhiteList whiteList : list) {
            executor.submit(() ->
                    saveWhiteList(sysUser.getInstitutionId(), whiteList, 1)
            );
        }
    }

}
